package com.example.filesystem.service;

import com.example.filesystem.dto.LoginRequest;
import com.example.filesystem.dto.RegisterRequest;
import com.example.filesystem.model.User;
import com.example.filesystem.repository.UserRepository;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class AuthService {

    private final AuthenticationManager authenticationManager;
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public AuthService(AuthenticationManager authenticationManager,
                       UserRepository userRepository,
                       PasswordEncoder passwordEncoder) {
        this.authenticationManager = authenticationManager;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    public void login(LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        loginRequest.getPassword()
                )
        );
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    @Transactional
    public void update(Long id, String password) {
        password = passwordEncoder.encode(password);
        userRepository.updateById(id, password);
    }

    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }

    public void checkUser(String username, String password) {
        authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        username, password
                )
        );
    }

    public Boolean userExist(String username) {
        return userRepository.existsByUsername(username);
    }

    public boolean register(RegisterRequest registerRequest) {
        if (usernameExists(registerRequest.getUsername())) {
            return false;
        }
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
        user.setRoles(Collections.singleton("USER"));

        userRepository.save(user);
        return true;
    }

    public boolean usernameExists(String username) {
        return userRepository.existsByUsername(username);
    }
}